package cn.cmcc.online.smsapi.ui.web.help;

import android.util.Log;
import android.webkit.JsPromptResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

import cn.cmcc.online.smsapi.ui.web.widget.SdkWebView;

/**
 * 辅助WebView处理JavaScript的对话框、网站图标、网站title、加载进度等
 */
public class WebChromeClientHelper extends WebChromeClient {
    private static final String TAG = WebChromeClientHelper.class.getSimpleName();

    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        injectJavascriptInterfaces(view);
        super.onProgressChanged(view, newProgress);
    }

    @Override
    public boolean onJsPrompt(WebView view, String url, String message,
                              String defaultValue, JsPromptResult result) {
        try {
            if (view instanceof SdkWebView) {
                SdkWebView webView = (SdkWebView) view;
                if (webView.handleJsInterface(message, result)) {
                    return true;
                }
            }
        } catch (Throwable e) {
            Log.e(TAG, "onJsPrompt, e =" + e);
        }
        return super.onJsPrompt(view, url, message, defaultValue, result);
    }

    @Override
    public void onReceivedTitle(WebView view, String title) {
        injectJavascriptInterfaces(view);
    }

    private void injectJavascriptInterfaces(WebView view) {
        try {
            if (view instanceof SdkWebView) {
                SdkWebView webView = (SdkWebView) view;
                webView.injectJavascriptInterfaces();
            }
        } catch (Throwable e) {
            Log.e(TAG, "injectJavascriptInterfaces, e =" + e);
        }
    }
}
